using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiBuilder.Models;
using MauiBuilder.Services;
using System.Collections.ObjectModel;

namespace MauiBuilder.ViewModels;

public partial class PaymentViewModel : BaseViewModel
{
    private readonly IPaymentManagerService _paymentManagerService;

    [ObservableProperty]
    private bool isLoading = false;

    [ObservableProperty]
    private string statusMessage = string.Empty;

    [ObservableProperty]
    private PaymentRequest currentOrder;

    [ObservableProperty]
    private PaymentType selectedPaymentType = PaymentType.Alipay;

    [ObservableProperty]
    private string payButtonText = "立即支付";

    [ObservableProperty]
    private ObservableCollection<PaymentHistoryItem> paymentHistory = new();

    public PaymentViewModel(IPaymentManagerService paymentManagerService)
    {
        _paymentManagerService = paymentManagerService;
        InitializeOrder();
        UpdatePayButtonText();
    }

    private void InitializeOrder()
    {
        CurrentOrder = new PaymentRequest
        {
            OrderId = GenerateOrderId(),
            Subject = "测试商品",
            Body = "这是一个测试商品的描述",
            Amount = 0.01m, // 测试金额
            NotifyUrl = "https://your-domain.com/payment/notify",
            ReturnUrl = "https://your-domain.com/payment/return",
            PaymentType = SelectedPaymentType
        };
    }

    [RelayCommand]
    private void SelectPaymentType(string paymentType)
    {
        if (Enum.TryParse<PaymentType>(paymentType, out var type))
        {
            SelectedPaymentType = type;
            CurrentOrder.PaymentType = type;
            UpdatePayButtonText();
        }
    }

    private void UpdatePayButtonText()
    {
        PayButtonText = SelectedPaymentType switch
        {
            PaymentType.Alipay => "支付宝支付",
            PaymentType.WeChatPay => "微信支付",
            _ => "立即支付"
        };
    }

    [RelayCommand]
    private async Task PayAsync()
    {
        if (IsLoading) return;

        IsLoading = true;
        StatusMessage = "正在发起支付...";

        try
        {
            var result = await _paymentManagerService.PayAsync(CurrentOrder);
            
            StatusMessage = result.IsSuccess ? "支付成功" : $"支付失败: {result.Message}";
            
            // 添加到支付历史
            await AddToPaymentHistory(result);
        }
        catch (Exception ex)
        {
            StatusMessage = $"支付异常: {ex.Message}";
            await ShowAlert("支付异常", ex.Message);
        }
        finally
        {
            IsLoading = false;
        }
    }

    private async Task AddToPaymentHistory(PaymentResponse result)
    {
        var historyItem = new PaymentHistoryItem
        {
            OrderId = result.OrderId,
            Amount = CurrentOrder.Amount,
            Status = result.IsSuccess ? "成功" : "失败",
            StatusColor = result.IsSuccess ? Colors.Green : Colors.Red,
            PaymentTime = DateTime.Now
        };
        PaymentHistory.Insert(0, historyItem);

        // 限制历史记录数量
        while (PaymentHistory.Count > 10)
        {
            PaymentHistory.RemoveAt(PaymentHistory.Count - 1);
        }

        if (result.IsSuccess)
        {
            await ShowAlert("支付成功", $"订单 {result.OrderId} 支付成功\n交易号: {result.TradeNo}");
            await OnPaymentSuccess(result);
        }
        else
        {
            await ShowAlert("支付失败", result.Message ?? "支付失败");
            await OnPaymentFailed(result);
        }
    }

    private PaymentConfig CreatePaymentConfig()
    {
        return SelectedPaymentType switch
        {
            PaymentType.Alipay => new PaymentConfig
            {
                PaymentType = PaymentType.Alipay,
                AppId = "your_alipay_app_id", // 从配置文件或安全存储获取
                ApiKey = "your_alipay_private_key",
                Environment = "sandbox", // 测试环境
                ExtendData = new Dictionary<string, object>
                {
                    ["partner_id"] = "your_partner_id",
                    ["seller_id"] = "your_seller_id"
                }
            },
            PaymentType.WeChatPay => new PaymentConfig
            {
                PaymentType = PaymentType.WeChatPay,
                AppId = "your_wechat_app_id", // 从配置文件或安全存储获取
                ApiKey = "your_wechat_api_key",
                Environment = "sandbox", // 测试环境
                ExtendData = new Dictionary<string, object>
                {
                    ["mch_id"] = "your_merchant_id",
                    ["api_key"] = "your_api_key"
                }
            },
            _ => throw new NotSupportedException($"不支持的支付类型: {SelectedPaymentType}")
        };
    }

    private async Task HandlePaymentResult(PaymentResponse result)
    {
        StatusMessage = result.Message;

        // 添加到支付历史
        var historyItem = new PaymentHistoryItem
        {
            OrderId = result.OrderId,
            Amount = CurrentOrder.Amount,
            Status = result.IsSuccess ? "成功" : "失败",
            StatusColor = result.IsSuccess ? Colors.Green : Colors.Red,
            PaymentTime = DateTime.Now
        };
        PaymentHistory.Insert(0, historyItem);

        // 限制历史记录数量
        while (PaymentHistory.Count > 10)
        {
            PaymentHistory.RemoveAt(PaymentHistory.Count - 1);
        }

        if (result.IsSuccess)
        {
            await ShowAlert("支付成功", $"订单 {result.OrderId} 支付成功\n交易号: {result.TradeNo}");
            await OnPaymentSuccess(result);
        }
        else
        {
            await ShowAlert("支付失败", result.Message);
            await OnPaymentFailed(result);
        }
    }

    private async Task OnPaymentSuccess(PaymentResponse result)
    {
        // 支付成功后的业务逻辑
        StatusMessage = "支付成功，正在处理订单...";
        
        // 这里可以添加：
        // 1. 更新订单状态
        // 2. 发送支付成功通知
        // 3. 跳转到成功页面
        // 4. 清空当前订单，生成新订单
        
        await Task.Delay(2000);
        RefreshOrder();
        StatusMessage = "订单处理完成";
    }

    private async Task OnPaymentFailed(PaymentResponse result)
    {
        // 支付失败后的业务逻辑
        StatusMessage = "支付失败，请重试或选择其他支付方式";
        
        // 这里可以添加：
        // 1. 记录失败日志
        // 2. 更新订单状态为失败
        // 3. 提供重新支付选项
        // 4. 分析失败原因并给出建议
        
        await Task.Delay(1000);
    }

    [RelayCommand]
    private async Task QueryPaymentAsync()
    {
        if (IsLoading) return;
        if (string.IsNullOrEmpty(CurrentOrder?.OrderId))
        {
            await ShowAlert("提示", "请先创建订单");
            return;
        }

        IsLoading = true;
        StatusMessage = "正在查询支付状态...";

        try
        {
            var result = await _paymentManagerService.QueryAsync(CurrentOrder.OrderId, SelectedPaymentType);
            
            StatusMessage = $"查询完成: {result.Message}";
            
            var statusText = result.Status switch
            {
                PaymentStatus.Pending => "待支付",
                PaymentStatus.Processing => "处理中",
                PaymentStatus.Success => "支付成功",
                PaymentStatus.Failed => "支付失败",
                PaymentStatus.Cancelled => "已取消",
                PaymentStatus.Refunded => "已退款",
                _ => "未知状态"
            };

            await ShowAlert("支付状态查询", 
                $"订单号: {result.OrderId}\n" +
                $"状态: {statusText}\n" +
                $"金额: ¥{result.Amount:F2}\n" +
                $"交易号: {result.TradeNo ?? "无"}");
        }
        catch (Exception ex)
        {
            StatusMessage = $"查询失败: {ex.Message}";
            await ShowAlert("查询失败", ex.Message);
        }
        finally
        {
            IsLoading = false;
        }
    }

    [RelayCommand]
    private void RefreshOrder()
    {
        InitializeOrder();
        StatusMessage = "订单已刷新";
        PaymentHistory.Clear();
    }

    private async Task ShowAlert(string title, string message)
    {
        await MainThread.InvokeOnMainThreadAsync(async () =>
        {
            var shell = Shell.Current;
            if (shell != null)
            {
                await shell.DisplayAlert(title, message, "确定");
            }
        });
    }

    private string GenerateOrderId()
    {
        return $"ORDER_{DateTime.Now:yyyyMMddHHmmss}_{new Random().Next(1000, 9999)}";
    }

    private string GetPaymentTypeName(PaymentType paymentType)
    {
        return paymentType switch
        {
            PaymentType.Alipay => "支付宝",
            PaymentType.WeChatPay => "微信支付",
            _ => "未知支付方式"
        };
    }

    partial void OnSelectedPaymentTypeChanged(PaymentType value)
    {
        UpdatePayButtonText();
        if (CurrentOrder != null)
        {
            CurrentOrder.PaymentType = value;
        }
    }
}

/// <summary>
/// 支付历史记录项
/// </summary>
public class PaymentHistoryItem
{
    public string OrderId { get; set; } = string.Empty;
    public decimal Amount { get; set; }
    public string Status { get; set; } = string.Empty;
    public Color StatusColor { get; set; } = Colors.Gray;
    public DateTime PaymentTime { get; set; }
}